package com.p900.website.web.admin;

import com.p900.commons.domain.Product;
import com.p900.commons.vo.BaseConditionVO;
import com.p900.website.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.constraints.NotNull;
import java.util.Map;

/**
 * Created by lenovo on 2015/5/2.
 */
@Controller("adminProduct")
@RequestMapping("/admin")
public class ProductController {

    @Autowired
    private ProductService productService;


    @RequestMapping("/product/list/{platformId}")
    public String list(@PathVariable @NotNull Long platformId,
                       BaseConditionVO vo,
                       Model model){
        Page<Product> productPage = productService.findByPlatformId(platformId, new PageRequest(vo.getPageNum() - 1, vo.getPageSize()));

        model.addAttribute("products", productPage);
        vo.setTotalCount(productPage.getTotalElements());
        model.addAttribute("vo", vo);

        return "admin/product/list";
    }

    @RequestMapping("/product/add/{platformId}")
    public String add(@PathVariable Long platformId,
                      Model model){
        model.addAttribute("platformId", platformId);
        return "admin/product/add";
    }

    @RequestMapping("/product/edit/{id}")
    public String edit(@PathVariable Long id,
                       Model model){
        model.addAttribute("product", productService.findProduct(id));
        return "admin/product/edit";
    }

    @ResponseBody
    @RequestMapping("/product/save")
    public Object save(Product product){
        Assert.notNull(product, "product is null");
        productService.save(product);
        return DwzResultVo.successResult();
    }

    @ResponseBody
    @RequestMapping("/product/delete/{id}")
    public Object delete(@PathVariable Long id){
        productService.delete(id);
        return DwzResultVo.successResult();
    }
}
